package jdbc05;

import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class JDBCUtils {
    private JDBCUtils() {
    }
    private static String driver;
    private static String url;
    private static String user;
    private static String password;
    static {
        Properties properties = new Properties();
        InputStream is =
                JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");
        try {
            /*从流中将配置文件中的数据加载到集合中*/
            properties.load(is);
            /*从这个集合中根据 key 获取对应的 value 初始化数据库参数*/
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            user = properties.getProperty("user");
            password = properties.getProperty("password");
            Class.forName(driver);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConnection() {
        Connection conn=null;
        try {
            conn= DriverManager.getConnection(url, user, password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /*释放资源*/
    public static void release(Connection con, Statement statement, ResultSet rs)
    {
        if (con!=null) {//避免空指针异常
            try {
                con.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }

        }
        if (statement!=null) {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
